var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
//var StatsPlugin = require("stats-webpack-plugin");

module.exports = function(options) {
	var _entry = [
		'./src/index'
	];
	var _preLoaders = {
		"js":"eslint-loader"
	};
	var _loaders = {
		"js": {
			loaders: ['babel'],
			include: path.join(__dirname, 'src')
		},
		"less":ExtractTextPlugin.extract("style", "css!less")
	};
	var _output = {
		path: path.join(__dirname, 'bundles'),
		filename: 'app.js',
		publicPath: '/bundles/'
	};
	var _plugins = [new ExtractTextPlugin("app.css")];

	if(options.hotdev==true){
		_entry = [
			'webpack-dev-server/client?http://127.0.01:3000', // WebpackDevServer host and port
			'webpack/hot/only-dev-server'].concat(_entry);

		_loaders.js.loaders = ['react-hot'].concat(_loaders.js.loaders);
		_plugins = [new webpack.HotModuleReplacementPlugin()].concat(_plugins);
	}
	return {
		entry: _entry,
		output: _output,
		module: {
			preLoaders:loadersByExtension(_preLoaders),
			loaders: loadersByExtension(_loaders)
		},
		plugins: _plugins
	};
};


function extsToRegExp(exts) {
	return new RegExp("\\.(" + exts.map(function(ext) {
			return ext.replace(/\./g, "\\.");
		}).join("|") + ")(\\?.*)?$");
}

function loadersByExtension (obj) {
	var loaders = [];
	Object.keys(obj).forEach(function(key) {
		var exts = key.split("|");
		var value = obj[key];
		var entry = {
			extensions: exts,
			test: extsToRegExp(exts)
		};
		if(Array.isArray(value)) {
			entry.loaders = value;
		} else if(typeof value === "string") {
			entry.loader = value;
		} else {
			Object.keys(value).forEach(function(valueKey) {
				entry[valueKey] = value[valueKey];
			});
		}
		loaders.push(entry);
	});
	return loaders;
};
